﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
#if NativeCov
using ExcelRef = Microsoft.Office.Interop.Excel;
#endif
using System.IO;
using System.Threading;
using System.Configuration;

namespace FX.CC.Andon.EqKanban
{
    public partial class frmViewDoc : Form
    {
        int pdfPageCount = 0, currentPage = 1;
        string webBasePath;
        DocWrapper docObj;

        Action actDataReady;

        Action actOpPlayed;

        Action actCheckPlayed;

        bool showOpDoc, showCheckDoc;

        public frmViewDoc(DocWrapper doc)
        {
            InitializeComponent();
            docObj = doc;

            showOpDoc = !string.IsNullOrEmpty(doc.OpDispPages);
            showCheckDoc = !string.IsNullOrEmpty(doc.ChkDispPages);

            this.webBasePath = ConfigurationManager.AppSettings["WebBasePath"];

            actDataReady = new Action(() => {
                if (showOpDoc)
                {
#if NativeCov
                    axAcroPDF1.LoadFile(docObj.OpFileExcel + ".PDF");
#endif
                    axAcroPDF1.LoadFile(docObj.OpFileExcel);
                    axAcroPDF1.setShowScrollbars(false);
                    IList<int> pages = docObj.OpDispPages.Split(';').Select(p => Convert.ToInt32(p)).ToList();
                    ThreadPool.QueueUserWorkItem(PlayOpDoc, pages);
                }
                else {
                    actOpPlayed.Invoke();
                }
            });

            actOpPlayed = new Action (() => {
                if (showCheckDoc)
                {
#if NativeCov
                    axAcroPDF1.LoadFile(docObj.CheckFileExcel + ".PDF");
#endif
                    axAcroPDF1.LoadFile(docObj.CheckFileExcel);
                    axAcroPDF1.setShowScrollbars(false);
                    IList<int> pages = docObj.ChkDispPages.Split(';').Select(p => Convert.ToInt32(p)).ToList();
                    ThreadPool.QueueUserWorkItem(PlayCheckDoc, pages);
                }
                else {
                    actCheckPlayed.Invoke();
                }
            });

            actCheckPlayed = new Action(()=>{ this.Close(); });

            ThreadPool.QueueUserWorkItem(GetAndConvertFile);
        }

        void GetAndConvertFile(object obj) {
            if(showOpDoc){
                docObj.OpFile = docObj.OpFile.StartsWith("/") ? docObj.OpFile : ("/" + docObj.OpFile);
                string opFileUrl = webBasePath + docObj.OpFile;

                docObj.OpFileExcel = Application.StartupPath + "\\Doc\\" + docObj.OpFile.Split('/').Last();
                try
                {
#if NativeCov
                    if (!File.Exists(docObj.OpFileExcel))
                    {
                        HttpFile.Download(opFileUrl, docObj.OpFileExcel);
                    }

                    if (!File.Exists(docObj.OpFileExcel + ".PDF"))
                    {
                        ExcelToPDF(docObj.OpFileExcel, docObj.OpFileExcel + ".PDF");
                    }
#endif
                    if (!File.Exists(docObj.OpFileExcel))
                    {
                        HttpFile.Download(opFileUrl, docObj.OpFileExcel);
                    }
                }
                catch { }
            }

            if (showCheckDoc)
            {
                docObj.CheckFile = docObj.CheckFile.StartsWith("/") ? docObj.CheckFile : ("/" + docObj.CheckFile);
                string checkFileUrl = webBasePath + docObj.CheckFile;

                docObj.CheckFileExcel = Application.StartupPath + "\\Doc\\" + docObj.CheckFile.Split('/').Last();
                try
                {
#if NativeCov
                    if (!File.Exists(docObj.CheckFileExcel))
                    {
                        HttpFile.Download(checkFileUrl, docObj.CheckFileExcel);
                    }

                    if (!File.Exists(docObj.CheckFileExcel + ".PDF"))
                    {
                        ExcelToPDF(docObj.CheckFileExcel, docObj.CheckFileExcel + ".PDF");
                    }
#endif
                    if (!File.Exists(docObj.CheckFileExcel))
                    {
                        HttpFile.Download(checkFileUrl, docObj.CheckFileExcel);
                    }
                }
                catch { }
            }

            this.BeginInvoke(actDataReady);
        }

        void PlayOpDoc(object o) {
            //Thread.Sleep(1000);
            IList<int> pages = o as IList<int>;
            foreach (var page in pages) {
                this.BeginInvoke(new Action<int>(p => { axAcroPDF1.setCurrentPage(p); }), page);
                Thread.Sleep(20000);
            }

            this.BeginInvoke(actOpPlayed);
        }

        void PlayCheckDoc(object o)
        {
            //Thread.Sleep(1000);
            IList<int> pages = o as IList<int>;
            foreach (var page in pages)
            {
                this.BeginInvoke(new Action<int>((p) => { axAcroPDF1.setCurrentPage(p); }), page);
                Thread.Sleep(20000);
            }

            this.BeginInvoke(actCheckPlayed);
        }

#if NativeCov
        void ExcelToPDF(string srcFilePath, string targetFilePath)
        {
            ExcelRef.Application excelApplication = new ExcelRef.Application();
            excelApplication.ShowWindowsInTaskbar = false;
            ExcelRef.Workbook excelWorkBook = null;

            object paramMissing = Type.Missing;

            ExcelRef.XlFixedFormatType paramExportFormat = ExcelRef.XlFixedFormatType.xlTypePDF;
            ExcelRef.XlFixedFormatQuality paramExportQuality =
                ExcelRef.XlFixedFormatQuality.xlQualityMinimum;
            bool paramOpenAfterPublish = false;
            bool paramIncludeDocProps = false;
            bool paramIgnorePrintAreas = false;
            object paramFromPage = Type.Missing;
            object paramToPage = Type.Missing;

            try
            {
                // Open the source workbook.
                excelWorkBook = excelApplication.Workbooks.Open(srcFilePath,
                    paramMissing, paramMissing, paramMissing, paramMissing,
                    paramMissing, paramMissing, paramMissing, paramMissing,
                    paramMissing, paramMissing, paramMissing, paramMissing,
                    paramMissing, paramMissing);

                // Save it in the target format.
                if (excelWorkBook != null)
                    excelWorkBook.ExportAsFixedFormat(paramExportFormat,
                        targetFilePath, paramExportQuality,
                        paramIncludeDocProps, paramIgnorePrintAreas, paramFromPage,
                        paramToPage, paramOpenAfterPublish,
                        paramMissing);
            }
            catch (Exception ex)
            {
                // Respond to the error.
            }
            finally
            {
                // Close the workbook object.
                if (excelWorkBook != null)
                {
                    excelWorkBook.Close(false, paramMissing, paramMissing);
                    excelWorkBook = null;
                }

                // Quit Excel and release the ApplicationClass object.
                if (excelApplication != null)
                {
                    excelApplication.Quit();
                    excelApplication = null;
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }  
        }
#endif
    }

    public class PDFHelper
    {
        #region 获取PDF文件的页数
        private static int BytesLastIndexOf(Byte[] buffer, int length, string Search)
        {
            if (buffer == null)
                return -1;
            if (buffer.Length <= 0)
                return -1;
            byte[] SearchBytes = Encoding.Default.GetBytes(Search.ToUpper());
            for (int i = length - SearchBytes.Length; i >= 0; i--)
            {
                bool bFound = true;
                for (int j = 0; j < SearchBytes.Length; j++)
                {
                    if (ByteUpper(buffer[i + j]) != SearchBytes[j])
                    {
                        bFound = false;
                        break;
                    }
                }
                if (bFound)
                    return i;
            }
            return -1;
        }

        private static byte ByteUpper(byte byteValue)
        {
            char charValue = Convert.ToChar(byteValue);
            if (charValue < 'a' || charValue > 'z')
                return byteValue;
            else
                return Convert.ToByte(byteValue - 32);
        }
        /**/
        /// <summary>
        /// 获取pdf文件的页数
        /// </summary>
        ///
        public static int GetPDFPageCount(string path) //获取pdf文件的页数
        {
            byte[] buffer = File.ReadAllBytes(path);
            int length = buffer.Length;
            if (buffer == null)
                return -1;
            if (buffer.Length <= 0)
                return -1;
            try
            {
                //Sample
                //      29 0 obj
                //      <</Count 9
                //      Type /Pages
                int i = 0;
                int nPos = BytesLastIndexOf(buffer, length, "/Type/Pages");
                if (nPos == -1)
                    return -1;
                string pageCount = null;
                for (i = nPos; i < length - 10; i++)
                {
                    if (buffer[i] == '/' && buffer[i + 1] == 'C' && buffer[i + 2] == 'o' && buffer[i + 3] == 'u' && buffer[i + 4] == 'n' && buffer[i + 5] == 't')
                    {
                        int j = i + 3;
                        while (buffer[j] != '/' && buffer[j] != '>')
                            j++;
                        pageCount = Encoding.Default.GetString(buffer, i, j - i);
                        break;
                    }
                }
                if (pageCount == null)
                    return -1;
                int n = pageCount.IndexOf("Count");
                if (n > 0)
                {
                    pageCount = pageCount.Substring(n + 5).Trim();
                    for (i = pageCount.Length - 1; i >= 0; i--)
                    {
                        if (pageCount[i] >= '0' && pageCount[i] <= '9')
                        {
                            return int.Parse(pageCount.Substring(0, i + 1));
                        }
                    }
                }
                return -1;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }
        #endregion
    }
}
